package com.sm.honkon.ui.model

import androidx.lifecycle.viewModelScope
import au.com.safie.user.app.util.CacheUtil
import com.blankj.utilcode.util.ToastUtils
import com.sm.honkon.app.App
import com.sm.honkon.data.bean.HandlerEntity
import com.sm.honkon.data.bean.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.util.notNull

class LoginViewModel:BaseViewModel() {

    val admin: UserInfo? = CacheUtil.getUser()
    val mobile = StringObservableField()
    val password = StringObservableField()
    val reset = StringObservableField("验证登录")
    val adminLogin = BooleanObservableField(false)

    fun isAdminLogin(isAdminLogin:Boolean){
        adminLogin.set(isAdminLogin)
        reset.set(if(isAdminLogin) "重置密码" else "验证登录")
    }

    fun login(function: (HandlerEntity?) -> Unit) {
        val mobile = mobile.get()
        val password = password.get()
        if (mobile.isEmpty()) {
            ToastUtils.showShort("请输入手机号/工号")
            return
        }
        if (password.isEmpty()) {
            ToastUtils.showShort("请输入密码")
            return
        }
        admin?.takeIf {
            adminLogin.get()
        }.notNull(
            {
                if (it.password != password) {
                    ToastUtils.showShort("密码不正确")
                } else {
                    function.invoke(null)
                }
            }, {
                viewModelScope.launch(Dispatchers.Main) {
                    val handlers =
                        withContext(Dispatchers.Default) {
                            App.database.handleDao().getHandlersList()
                        }
                    handlers.find {
                        it.mobile == mobile || it.workId == mobile
                    }.notNull(
                        {
                            if (it.password != password) {
                                ToastUtils.showShort("密码不正确")
                            } else if(it.status == 1){
                                ToastUtils.showShort("用户已被禁用")
                            } else {
                                function.invoke(it)
                            }
                        }, {
                            ToastUtils.showShort("账号不存在")
                        }
                    )
                }
            }
        )
    }
}